#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import String
from cv_bridge import CvBridge
from pyzbar.pyzbar import decode
import cv2

class QRCodeScanner:
    def __init__(self):
        # 初始化ROS节点
        rospy.init_node('qr_code_scanner', anonymous=True)
        
        # 创建CV桥
        self.bridge = CvBridge()
        
        # 创建一个发布者，发布到/qr_back话题
        self.pub = rospy.Publisher('/qr_back', String, queue_size=10)
        
        # 订阅摄像头图像话题
        self.image_sub = rospy.Subscriber("/camera/color/image_raw", Image, self.image_callback)
        
        # 订阅qr话题
        self.sub = rospy.Subscriber("qr", String, self.qr_callback)
        
        # 扫描标志
        self.scanning = False

    def qr_callback(self, data):
        zhiling = data.data
        if "scan" in zhiling:
            rospy.loginfo("Received scan command, starting QR code scanning...")
            self.scanning = True

    def image_callback(self, data):
        if not self.scanning:
            return
            
        try:
            # 将ROS图像消息转换为OpenCV格式
            cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8")
            
            # 显示摄像头画面
            cv2.imshow('QR Code Scanner', cv_image)
            cv2.waitKey(1)  # 避免窗口卡死

            # 解析二维码
            decoded_objects = decode(cv_image)
            for obj in decoded_objects:
                qr_data = obj.data.decode('utf-8')
                rospy.loginfo("QR Code Data: %s", qr_data)
                
                # 发布二维码数据到/qr_back话题
                self.pub.publish(qr_data)
                self.scanning = False  # 识别到二维码后，停止扫描
                
        except Exception as e:
            rospy.logerr("Error processing image: %s", str(e))

    def run(self):
        rospy.spin()
        cv2.destroyAllWindows()

if __name__ == '__main__':
    try:
        scanner = QRCodeScanner()
        scanner.run()
    except rospy.ROSInterruptException:
        pass
    finally:
        cv2.destroyAllWindows()
